package com.kingmed.kmss.admin.modules.ums.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingmed.kmss.admin.modules.ums.mapper.UmsAdminMapper;
import com.kingmed.kmss.admin.modules.ums.model.*;
import com.kingmed.kmss.admin.modules.ums.service.*;
import com.kingmed.kmss.admin.qc.AdminQc;
import com.kingmed.kmss.common.constant.common.CommonConstants;
import com.kingmed.kmss.common.dto.admin.ums.*;
import com.kingmed.kmss.common.enums.admin.UserSource;
import com.kingmed.kmss.common.exception.BusinessException;
import com.kingmed.kmss.common.satoken.LoginHelper;
import com.kingmed.kmss.common.utils.BeanCopyUtils;
import com.kingmed.kmss.common.utils.MessageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {

    @Autowired
    private UmsAdminLoginLogService adminLoginLogService;
    @Autowired
    private UmsAdminRoleRelationService adminRoleRelationService;
    @Autowired
    private UmsAdminCacheService umsAdminCacheService;
    @Autowired
    private UmsAdminOrganizationRelationService organizationRelationService;
    @Autowired
    private UmsOrganizationService organizationService;
    @Autowired
    private UmsOrganizationService umsOrganizationService;
    @Autowired
    private UmsAdminOrganizationRelationService umsAdminOrganizationRelationService;

    /**
     * 默认pc端注册
     */
    @Override
    public UmsAdmin register(AdminRegisterDTO adminRegisterDto) {

        UmsAdmin admin = new UmsAdmin();
        BeanCopyUtils.copy(adminRegisterDto, admin);
        admin.setUserSource(UserSource.CRM_USER.getUserType());
        admin.setStatus(CommonConstants.FLG_YES);
        //查询是否有相同用户名的用户
        List<UmsAdmin> adminList = this.list(new QueryWrapper<UmsAdmin>().lambda().eq(UmsAdmin::getUsername, admin.getUsername()));
        if (!adminList.isEmpty()) {
            return null;
        }
        //将密码进行加密操作
        String encodePassword = SaSecureUtil.md5(admin.getPassword());
        admin.setPassword(encodePassword);
        //自动填充create和update
        save(admin);

        this.addOrgRelation(admin, CommonConstants.ORG_ROOT_P);
        return admin;
    }

    @Override
    public SaTokenInfo login(String username, String password) {
        //验证用户名
        UmsAdmin admin = this.getBaseMapper().selectUserByUsername(username);
        if (admin == null) {
            return null;
        }
        //验证密码
        if (!admin.getPassword().equals(SaSecureUtil.md5(password))) {
            return null;
        }
        //在分布式/微服务环境下用缓存redis来存储session，在多个微服务间共享（此session非传统的session）
        AdminAuthDTO adminAuthDto = loadAdminAuthDtoByUsername(username);
        LoginUserDTO loginUser = new LoginUserDTO();
        //深拷贝，目前adminAuthDto=loginUser
        BeanCopyUtils.copy(adminAuthDto, loginUser);
        //执行sa-token登录，set到redis
        LoginHelper.login(loginUser);
        insertLoginLog(admin.getId(), "登录");
        //最后生成token
        return StpUtil.getTokenInfo();
    }

    //第一次登录时获取Admin,转换成AdminAuthDto，以便set到redis session
    public AdminAuthDTO loadAdminAuthDtoByUsername(String username) {
        UmsAdmin admin = selectUserByUsername(username);
        if (admin == null) {
            return null;
        }
        return createFullAdminDTO(admin);
    }

    private AdminAuthDTO createFullAdminDTO(UmsAdmin admin) {
        Long adminId = admin.getId();
        AdminAuthDTO adminAuthDto = new AdminAuthDTO();
        BeanCopyUtils.copy(admin, adminAuthDto);
        //用于记录当前登录人的user_id
        adminAuthDto.setUserId(adminId);

        // 用户对应角色
        List<UmsRole> roleList1 = getRoleList(admin.getId());
        admin.setRoles(roleList1);
        if (roleList1 != null && !roleList1.isEmpty()) {
            List<String> roleList = roleList1.stream()
                    .filter(role -> role.getRoleKey() != null)
                    .map(UmsRole::getRoleKey)
                    .collect(Collectors.toList());
            adminAuthDto.setRoleList(roleList);
            //umsrole to roledto
            List<RoleDTO> roles = BeanUtil.copyToList(roleList1, RoleDTO.class);
            adminAuthDto.setRoles(roles);
        }

        // 用户对应菜单
        List<UmsMenu> menuList1 = getMenuList(admin.getId());
        admin.setMenus(menuList1);
        if (menuList1 != null && !menuList1.isEmpty()) {
            List<String> menuList = menuList1.stream()
                    .filter(menu -> menu.getName() != null)
                    .map(UmsMenu::getName)
                    .collect(Collectors.toList());
            adminAuthDto.setMenuList(menuList);
            //umsmenu to menudto
            List<MenuDTO> menus = BeanUtil.copyToList(menuList1, MenuDTO.class);
            adminAuthDto.setMenus(menus);

            //用户有权限菜单树形
            List<MenuNodeDTO> menuNodes = menuList1.stream()
                    .filter(menu -> menu.getParentId().equals(CommonConstants.MENU_ROOT_P))
                    .map(menu -> covertMenuNode(menu, menuList1)).collect(Collectors.toList());
            adminAuthDto.setMenusTree(BeanUtil.copyToList(menuNodes, MenuNodeDTO.class));
        }

        // 用户对应资源
        List<UmsResource> resourceList1 = getResourceList(admin.getId(), null);
        admin.setResources(resourceList1);
        if (resourceList1 != null && !resourceList1.isEmpty()) {
            List<String> resourceList = resourceList1.stream()
                    .filter(resource -> resource.getCode() != null)
                    .map(UmsResource::getCode)
                    .collect(Collectors.toList());
            adminAuthDto.setResourceList(resourceList);
            //umsresource to resourcedto
            List<ResourceDTO> resources = BeanUtil.copyToList(resourceList1, ResourceDTO.class);
            adminAuthDto.setResources(resources);
        }

        // 用户对应组织部门
        List<UmsOrganization> organizations1 = this.getOrgList(admin.getId());
        if (organizations1 != null && !organizations1.isEmpty()) {
            admin.setOrganizations(organizations1);

            List<String> orgList = organizations1.stream()
                    .filter(organization -> organization.getOrgCode() != null)
                    .map(UmsOrganization::getOrgCode)
                    .collect(Collectors.toList());
            adminAuthDto.setOrgList(orgList);

            adminAuthDto.setOrgs(BeanUtil.copyToList(organizations1, OrganizationDTO.class));
        }
        return adminAuthDto;
    }

    /**
     * 将UmsMenu转化为UmsMenuNode并设置children属性
     */
    private MenuNodeDTO covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
        MenuNodeDTO node = new MenuNodeDTO();
        BeanUtils.copyProperties(menu, node);

        MenuMetaDTO menuMetaDto = new MenuMetaDTO();
        menuMetaDto.setTitle(menu.getTitle());
        menuMetaDto.setRank(menu.getSort());
        menuMetaDto.setIcon(menu.getIcon());
        menuMetaDto.setShowParent(menu.getShowParent() == CommonConstants.FLG_YES);
        menuMetaDto.setShowLink(menu.getShowLink() == CommonConstants.FLG_YES);
        menuMetaDto.setNeedCache(ObjectUtil.isNotNull(menu.getNeedCache()) && menu.getNeedCache() == CommonConstants.FLG_YES);
        node.setMeta(menuMetaDto);

        List<MenuNodeDTO> children = menuList.stream()
                .filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
                .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }

    @Override
    public LoginUserDTO getAdminDTOByIdInCache(Long id) {
        //从缓存
        LoginUserDTO loginUser = LoginHelper.getLoginUser();
        if (ObjectUtil.isNull(loginUser)) {
            //从数据库
            UmsAdmin admin = getById(id);
            if (admin != null) {
                loginUser = (LoginUserDTO) createFullAdminDTO(admin);
            }
        }
        return loginUser;
    }

    @Override
    public List<UmsResource> getResourceList(Long userId, Long menuId) {
        return this.getBaseMapper().getResourceList(userId, menuId);
    }

    @Override
    public List<UmsMenu> getMenuList(Long userId) {
        return this.getBaseMapper().getMenuList(userId);
    }

    @Override
    public List<UmsRole> getRoleList(Long id) {
        return this.getBaseMapper().getRoleList(id);
    }

    @Override
    public Page<AdminDTO> pageDtoList(AdminQc adminQc, Page<UmsAdmin> page) {
        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<UmsAdmin> lambda = wrapper.lambda();
        String username = adminQc.getUsername();
        if (StrUtil.isNotEmpty(username)) {
            lambda.and(Wrapper ->
                    Wrapper.like(UmsAdmin::getUsername, username)
                            .or().like(UmsAdmin::getNickName, username)
                            .or().like(UmsAdmin::getEmployeeNum, username));
        }
        if (adminQc.getStatus() != null) {
            lambda.eq(UmsAdmin::getStatus, adminQc.getStatus());
        }
        if (StrUtil.isNotBlank(adminQc.getEmpStatus())) {
            lambda.eq(UmsAdmin::getEmpStatus, adminQc.getEmpStatus());
        }
        return this.toDtoPage(this.page(page, wrapper));
    }

    private Page<AdminDTO> toDtoPage(Page<UmsAdmin> adminPage) {
        Page<AdminDTO> dtoPage = new Page<>(adminPage.getCurrent(), adminPage.getSize(), adminPage.getTotal(), adminPage.searchCount());
        if (CollectionUtils.isEmpty(adminPage.getRecords())) {
            return dtoPage;
        }
        List<AdminDTO> dtoList = new ArrayList<>();
        for (UmsAdmin record : adminPage.getRecords()) {
            AdminDTO dto = BeanCopyUtils.copy(record, AdminDTO.class);

            List<UmsOrganization> userOrgList = this.getOrgList(record.getId());
            if (CollectionUtils.isNotEmpty(userOrgList)) {
                dto.setOrganizations(BeanCopyUtils.copyList(userOrgList, OrganizationDTO.class));

                if (UserSource.CRM_USER.getUserType().equals(record.getUserSource())) {
                    dto.setOrgFullName(organizationService.getAdminOrgFullName(userOrgList.get(0).getId()));
                }
            }
            dtoList.add(dto);
        }
        dtoPage.setRecords(dtoList);
        return dtoPage;
    }

    /**
     * 根据条件全量查询用户
     */
    @Override
    public List<AdminDTO> queryAll(AdminQc adminQc) {
        return BeanCopyUtils.copyList(this.getBaseMapper().selectByNameKeyWord(adminQc.getUsername()), AdminDTO.class);
    }

    /**
     * 先根据username从redis取，没有就查数据库，并按照username set到redis
     */
    @Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdmin admin = umsAdminCacheService.getAdmin(username);
        if (admin != null) return admin;
        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UmsAdmin::getUsername, username);
        List<UmsAdmin> adminList = list(wrapper);
        if (adminList != null && !adminList.isEmpty()) {
            admin = adminList.get(0);
            umsAdminCacheService.setAdmin(admin);
            return admin;
        }
        return null;
    }


    @Override
    public boolean update(Long id, UmsAdminCreateDTO admin) {
        //不更新orgid（org_id是系统保留字段）
        admin.setOrgId(null);
        UmsAdmin umsAdmin = BeanUtil.copyProperties(admin, UmsAdmin.class);
        umsAdmin.setId(id);
        UmsAdmin rawAdmin = getById(id);
        if (rawAdmin.getPassword().equals(umsAdmin.getPassword())) {
            //与原加密密码相同的不需要修改
            umsAdmin.setPassword(null);
        } else {
            //与原加密密码不同的需要加密修改
            //如果为空，不修改
            if (StrUtil.isEmpty(umsAdmin.getPassword())) {
                umsAdmin.setPassword(null);
            } else {
                //密码不为空，加密后存数据库
                umsAdmin.setPassword(SaSecureUtil.md5(admin.getPassword()));
            }
        }
        // 判断用户账号的状态
        umsAdmin.setStatus(UmsHrEmployeeServiceImpl.userOKStatusList.contains(umsAdmin.getEmpStatus()) ? 1 : 0);
        boolean success = updateById(umsAdmin);
        //删除redis缓存
        umsAdminCacheService.delAdmin(id);
        return success;
    }

    @Transactional
    @Override
    public boolean delete(Long id) {
        UmsAdmin rawAdmin = this.getById(id);
        if (UserSource.OA_USER.getUserType().equals(rawAdmin.getUserSource())) {
            throw new BusinessException(MessageUtils.message("ums_admin_notCrm"));
        }
        umsAdminCacheService.delAdmin(id);
        boolean success = removeById(id);
        umsAdminCacheService.delResourceList(id);
        // 删除与组织机构关系
        organizationRelationService.deleteByAdminId(id);
        return success;
    }

    @Transactional
    @Override
    public int updateRole(Long adminId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系
        QueryWrapper<UmsAdminRoleRelation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UmsAdminRoleRelation::getAdminId, adminId);
        adminRoleRelationService.remove(wrapper);
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<UmsAdminRoleRelation> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                UmsAdminRoleRelation roleRelation = new UmsAdminRoleRelation();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            adminRoleRelationService.saveBatch(list);
        }
        umsAdminCacheService.delResourceList(adminId);
        return count;
    }

    /**
     * 登录验证查数据库，不查缓存,返回比较完整的AdminAuthDto信息
     */
    @Override
    public AdminAuthDTO loginCheck(String username, String password) {
        //验证用户名
        UmsAdmin admin = this.getBaseMapper().selectUserByUsername(username);
        if (admin == null) {
            return null;
        }
        //验证密码
        if (StrUtil.isBlank(admin.getPassword()) || !admin.getPassword().equals(SaSecureUtil.md5(password))) {
            return null;
        }
        AdminAuthDTO adminAuthDto;
        try {
            adminAuthDto = loadAdminAuthDtoByUsername(username);
            //登录验证成功，插入登录日志
            insertLoginLog(adminAuthDto.getId(), "登录");
        } catch (Exception e) {
            log.error("发生异常", e);
            throw new BusinessException("初始化登录数据异常");
        }
        return adminAuthDto;
    }

    /**
     * OA单点登录验证后获取登录用户id
     *
     * @param oaLoginId 内部是工号，外包是手机号
     */
    @Override
    public AdminAuthDTO oaLogin(String oaLoginId) {
        UmsAdmin admin = this.getBaseMapper().oaLoginQuery(oaLoginId);
        if (ObjectUtil.isNull(admin)) {
            throw new BusinessException(String.format("用户【%s】不存在", oaLoginId));
        }
        //
        AdminAuthDTO adminAuthDto = loadAdminAuthDtoByUsername(admin.getUsername());
        //登录验证成功，插入登录日志
        insertLoginLog(adminAuthDto.getId(), "OA登录");
        return adminAuthDto;
    }

    @Override
    public int updatePassword(UpdateAdminPasswordParamDTO param) {
        //不能为空
        if (StrUtil.isEmpty(param.getUsername())
                //|| StrUtil.isEmpty(param.getOldPassword())
                || StrUtil.isEmpty(param.getNewPassword())) {
            return -1;
        }
        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UmsAdmin::getUsername, param.getUsername()).eq(UmsAdmin::getDeleteFlag, 0);

        List<UmsAdmin> adminList = list(wrapper);
        if (CollUtil.isEmpty(adminList)) {
            return -2;
        }
        //旧密码跟数据库记录不一样
        UmsAdmin umsAdmin = adminList.get(0);

        //oa用户的密码，原则上不允许修改，默认都是空，现在放开
//        if (UserSource.OA_USER.getUserType().equals(umsAdmin.getUserSource())) {
//            throw new BusinessException(MessageUtils.message("ums_admin_notCrm"));
//        }

        //密码重置不需要校验旧密码
        //String oldPasswordMd5 = SaSecureUtil.md5(param.getOldPassword());
        //if (!oldPasswordMd5.equals(umsAdmin.getPassword())) {
        //    return -3;
        //}
        umsAdmin.setPassword(SaSecureUtil.md5(param.getNewPassword()));
        updateById(umsAdmin);
        umsAdminCacheService.delAdmin(umsAdmin.getId());
        return 1;
    }

    /**
     * 添加登录记录
     *
     * @param id 用户名
     */
    private void insertLoginLog(Long id, String userAgent) {
        UmsAdminLoginLog loginLog = new UmsAdminLoginLog();
        loginLog.setAdminId(id);
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            loginLog.setIp(request.getRemoteAddr());
            loginLog.setAddress(request.getRemoteAddr());
            loginLog.setUserAgent(userAgent);
            adminLoginLogService.getBaseMapper().insert(loginLog);
        }
    }


    public UmsAdmin selectUserByUsername(String username) {
        return this.getBaseMapper().selectUserByUsername(username);
    }

    @Override
    public List<UmsOrganization> getOrgList(Long adminId) {
        return this.getBaseMapper().getOrgList(adminId);
    }

    @Transactional
    @Override
    public boolean create(UmsAdminCreateDTO admin) {

        Long adminOrgId = admin.getOrgId();

        this.checkUserName(admin.getUsername(), admin.getEmployeeNum());
        admin.setPassword(SaSecureUtil.md5(admin.getPassword()));
        admin.setUserSource(UserSource.CRM_USER.getUserType());
        //不能直接set成001,用前端传值（必填）
        //admin.setEmpStatus(UserStatus.OK.getCode());
        //不能直接set成001,根据EmpStatus
        admin.setStatus(UmsHrEmployeeServiceImpl.userOKStatusList.contains(admin.getEmpStatus()) ? 1 : 0);

        if (StrUtil.isBlank(admin.getEmployeeNum())) {
            admin.setEmployeeNum(admin.getUsername());
        }
        admin.setOrgFullName(organizationService.getAdminOrgFullName(adminOrgId));
        UmsAdmin umsAdmin = BeanUtil.copyProperties(admin, UmsAdmin.class);
        //前端传值，仅用于传关系,保存时删除
        umsAdmin.setOrgId(null);
        boolean success = this.save(umsAdmin);
        this.addOrgRelation(umsAdmin, adminOrgId);
        return success;
    }

    /**
     * 用户名称不能重复
     */
    private void checkUserName(String userName, String employeeNum) {
        List<UmsAdmin> adminList = this.list(new QueryWrapper<UmsAdmin>().lambda()
                .eq(UmsAdmin::getUsername, userName)
                .eq(UmsAdmin::getDeleteFlag, 0));
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(adminList))
            throw new BusinessException(MessageUtils.message("ums_admin_username_exist"));
        long count = this.count(new LambdaQueryWrapper<UmsAdmin>().eq(UmsAdmin::getEmployeeNum, employeeNum));
        if (count > 0)
            throw new BusinessException("员工号重复");
    }

    @Override
    public List<AdminDTO> queryByCondition(AdminQc adminQc) {
        List<UmsAdmin> adminList = this.list(new QueryWrapper<UmsAdmin>().lambda()
                .like(StrUtil.isNotEmpty(adminQc.getUsername()), UmsAdmin::getUsername, adminQc.getUsername())
                .like(StrUtil.isNotEmpty(adminQc.getEmployeeNum()), UmsAdmin::getEmployeeNum, adminQc.getEmployeeNum()));
        return BeanCopyUtils.copyList(adminList, AdminDTO.class);
    }

    /**
     * 更新用户与组织关系
     */
    private void addOrgRelation(UmsAdmin admin, Long orgId) {
        UmsAdminOrganizationRelation relation = new UmsAdminOrganizationRelation();
        relation.setAdminId(admin.getId());
        relation.setOrgId(orgId);
        organizationRelationService.save(relation);
    }

    @Override
    public AdminAuthDTO getAdminByOaLoginId(String oaLoginId) {
        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UmsAdmin::getOaId, oaLoginId);
        List<UmsAdmin> adminList = list(wrapper);
        if (adminList != null && !adminList.isEmpty()) {
            return BeanCopyUtils.copy(adminList.get(0), AdminAuthDTO.class);
        }
        return null;
    }

    /**
     * 条件精准查询
     */
    @Override
    public List<AdminDTO> queryByCondition(AdminQueryDTO queryDTO) {
        List<UmsAdmin> adminList = this.list(new QueryWrapper<UmsAdmin>().lambda()
                .eq(StrUtil.isNotEmpty(queryDTO.getPhone()), UmsAdmin::getPhone, queryDTO.getPhone())
                .eq(StrUtil.isNotEmpty(queryDTO.getEmpStatus()), UmsAdmin::getEmpStatus, queryDTO.getEmpStatus())
                .eq(StrUtil.isNotEmpty(queryDTO.getUsername()), UmsAdmin::getUsername, queryDTO.getUsername())
                .eq(StrUtil.isNotEmpty(queryDTO.getEmployeeNum()), UmsAdmin::getEmployeeNum, queryDTO.getEmployeeNum()));
        return BeanCopyUtils.copyList(adminList, AdminDTO.class);
    }

    @Override
    public List<AdminDTO> fuzzyQueryByName(String username) {
        List<UmsAdmin> adminList = this.list(new QueryWrapper<UmsAdmin>().lambda()
                .and(Wrapper -> Wrapper.like(UmsAdmin::getUsername, username)
                        .or().like(UmsAdmin::getNickName, username)
                        .or().like(UmsAdmin::getEmployeeNum, username))
                .eq(UmsAdmin::getDeleteFlag, 0)
                .eq(UmsAdmin::getStatus, 1)
                .last("limit 25"));
        List<AdminDTO> adminDTOS = BeanCopyUtils.copyList(adminList, AdminDTO.class);
        List<Long> adminIds = adminDTOS.stream().map(AdminDTO::getId).collect(Collectors.toList());
        if (adminIds == null || adminIds.isEmpty())
            return adminDTOS;
        List<UmsAdminOrganizationRelation> relation = umsAdminOrganizationRelationService.list(new LambdaQueryWrapper<UmsAdminOrganizationRelation>().in(UmsAdminOrganizationRelation::getAdminId, adminIds));
        if (relation == null || relation.isEmpty())
            return adminDTOS;
        for (AdminDTO dto :
                adminDTOS) {
            if (StringUtils.isBlank(dto.getOrgFullName())) {
                for (UmsAdminOrganizationRelation re :
                        relation) {
                    if (dto.getId().equals(re.getAdminId()))
                        dto.setOrgFullName(umsOrganizationService.getAdminOrgFullName(re.getOrgId()));
                }
            }
        }
        return adminDTOS;
    }

    @Override
    public List<AdminDTO> fuzzyQueryAllByName(String username) {
        List<UmsAdmin> adminList = this.list(new QueryWrapper<UmsAdmin>().lambda()
                .and(Wrapper -> Wrapper.like(UmsAdmin::getUsername, username)
                        .or().like(UmsAdmin::getNickName, username)
                        .or().like(UmsAdmin::getEmployeeNum, username))
                .eq(UmsAdmin::getDeleteFlag, 0)
                .eq(UmsAdmin::getStatus, 1));
        return BeanCopyUtils.copyList(adminList, AdminDTO.class);
    }

    @Override
    public AdminAuthDTO loadAdminAuthDtoByUsernameNew(String username) {
        //优先吧username当作员工号
        String finalUsername = username;
        QueryWrapper<UmsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().and(t -> t.eq(UmsAdmin::getEmployeeNum, finalUsername).or()
                        .eq(UmsAdmin::getUsername, finalUsername))
                .eq(UmsAdmin::getDeleteFlag, 0)
                .eq(UmsAdmin::getStatus, 1);
        List<UmsAdmin> umsAdmins = list(queryWrapper);
        if (CollUtil.isEmpty(umsAdmins)) {
            return null;
        }
        UmsAdmin admin = umsAdmins.get(0);
        return createFullAdminDTONew(admin);
    }

    private AdminAuthDTO createFullAdminDTONew(UmsAdmin admin) {
        Long adminId = admin.getId();
        AdminAuthDTO adminAuthDto = new AdminAuthDTO();
        BeanCopyUtils.copy(admin, adminAuthDto);
        //用于记录当前登录人的user_id
        adminAuthDto.setUserId(adminId);

        // 用户对应角色
        List<UmsRole> roleList1 = getRoleList(admin.getId());
        admin.setRoles(roleList1);
        if (roleList1 != null && !roleList1.isEmpty()) {
            List<String> roleList = roleList1.stream()
                    .filter(role -> role.getRoleKey() != null)
                    .map(UmsRole::getRoleKey)
                    .collect(Collectors.toList());
            adminAuthDto.setRoleList(roleList);
            //umsrole to roledto
            List<RoleDTO> roles = BeanUtil.copyToList(roleList1, RoleDTO.class);
            adminAuthDto.setRoles(roles);
        }

        // 用户对应组织部门
        List<UmsOrganization> organizations1 = this.getOrgList(admin.getId());
        if (organizations1 != null && !organizations1.isEmpty()) {
            admin.setOrganizations(organizations1);

            List<String> orgList = organizations1.stream()
                    .filter(organization -> organization.getOrgCode() != null)
                    .map(UmsOrganization::getOrgCode)
                    .collect(Collectors.toList());
            adminAuthDto.setOrgList(orgList);

            adminAuthDto.setOrgs(BeanUtil.copyToList(organizations1, OrganizationDTO.class));
        }
        return adminAuthDto;
    }

    @Override
    public OrganizationTileDTO getGroupRegionBranchByAdminId(Long adminId) {
        List<UmsOrganization> orgList = this.getOrgList(adminId);
        if (CollectionUtils.isEmpty(orgList)) {
            throw new BusinessException("当前用户没有分配部门");
        }
        // 一个用户只有一个组织
        return organizationService.getOrgGroupRegionBranchByOrgId(orgList.get(0).getId());
    }

    @Override
    public List<OrganizationDTO> getBranchesByAdminId(Long adminId) {
        List<UmsOrganization> orgList = this.getOrgList(adminId);
        if (CollectionUtils.isEmpty(orgList)) {
            throw new BusinessException("当前用户没有分配部门");
        }

        return organizationService.getBranchesByOrgId(orgList.get(0).getId());
    }

    @Override
    public OrganizationTileDTO getOrgTileByAdminId(Long adminId) {
        List<UmsOrganization> orgList = this.getOrgList(adminId);
        if (CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        // 一个用户只有一个组织
        return organizationService.getOrgGroupRegionBranchByOrgId(orgList.get(0).getId());
    }
}
